/*
 * measure.h
 *
 *  Created on: 2024年11月5日
 *      Author: zizhong
 */

#ifndef CONTROLLIB_MEASURE_H_
#define CONTROLLIB_MEASURE_H_

#include "foc_declare.h"
#include "driverlib.h"
#include "board.h"
#include "F2837xD_device.h"
#include "motor_para.h"



static float K1 = 0.998;         // Offset filter coefficient K1: 0.05/(T+0.05);
static float K2 = 0.001999;      // Offset filter coefficient K2: T/(T+0.05);

static inline float getVdc(MOTOR_Vars_t *ptrMotor)
{
    float vdc;

    vdc = 2457 * ptrMotor->voltageScale;

    if(vdc < 1.0)
    {
        vdc = 1.0;
    }

    return(vdc);
}

static inline void runOffsetsCalculation(MOTOR_Vars_t *pMotor)
{
    // Feedbacks OFFSET Calibration
    pMotor->offsetCalCounter++;
//    for(pMotor->offsetCalCounter = 0; pMotor->offsetCalCounter < 5000; pMotor->offsetCalCounter++)
//    {
//        EPWM_clearEventTriggerInterruptFlag(myEPWM2_BASE);
//
//        while(EPWM_getEventTriggerInterruptStatus(myEPWM2_BASE) == false);

        if((pMotor->offsetCalCounter > 1000) && (pMotor->offsetCalCounter < 10000))
        {
            // Offsets in phase current sensing
            pMotor->offset_currentCs  = (K1 * pMotor->offset_currentCs) +
                    (((float)(AdccResultRegs.ADCRESULT0)) * K2 * pMotor->adcScale);  //Ia

            pMotor->offset_currentBs  = (K1 * pMotor->offset_currentBs) +
                    (((float)(AdcbResultRegs.ADCRESULT0)) * K2 * pMotor->adcScale);  //Ib

            pMotor->offset_currentAs  = (K1 * pMotor->offset_currentAs) +
                    (((float)(AdcaResultRegs.ADCRESULT0)) * K2 * pMotor->adcScale);  //Ic

//            pMotor->fclPara.Vdcbus = getVdc(pMotor);
        }
//    }

        else if(pMotor->offsetCalCounter >= 10000)
        {
//            pMotor->fclPara.Vdcbus = getVdc(pMotor);
            // setting IA offset
            ADC_setPPBReferenceOffset(myADC2_BASE, ADC_PPB_NUMBER1,(uint16_t)(pMotor->offset_currentCs * ADC_RESOLUTION));
            // setting IB offset
            ADC_setPPBReferenceOffset(myADC1_BASE, ADC_PPB_NUMBER1,(uint16_t)(pMotor->offset_currentBs * ADC_RESOLUTION));
            // setting IC offset
            ADC_setPPBReferenceOffset(myADC0_BASE, ADC_PPB_NUMBER1,(uint16_t)(pMotor->offset_currentAs * ADC_RESOLUTION));
            // setting Vdc offset
//            ADC_setPPBReferenceOffset(myADC0_BASE, ADC_PPB_NUMBER2, 0);

            pMotor->offsetDoneFlag = 1;
        }

}

#endif /* CONTROLLIB_MEASURE_H_ */
